from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchWindowException
import time

MAX_RETRIES = 3


def check_unlock(driver):
    """检查并处理主窗口解锁"""
    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='password']"))
        )
        print("检测到主窗口需要解锁")

        password_input = driver.find_element(By.CSS_SELECTOR,
                                             "input[type='password'][placeholder='Enter your passcode']")
        password_input.send_keys("7758521love")
        print("已输入密码")

        unlock_button = driver.find_element(By.CSS_SELECTOR, "button.button-module_intent-primary__SAO1x")
        unlock_button.click()
        print("已点击解锁按钮")

        WebDriverWait(driver, 15).until(
            EC.invisibility_of_element_located((By.CSS_SELECTOR, "button.button-module_intent-primary__SAO1x"))
        )
        print("主窗口解锁成功")
        return True
    except TimeoutException:
        print("主窗口无需解锁或解锁超时")
        return False


def game_module_operations(driver):
    retries = 0
    main_window = driver.current_window_handle

    while retries < MAX_RETRIES:
        try:
            # 仅在首次进入循环时检查主窗口是否需要解锁
            if retries == 0:
                if check_unlock(driver):
                    print("主窗口已解锁，继续操作")
                else:
                    print("主窗口无需解锁")

            # 定位并点击第一个元素（Create account）
            target_div_xpath = "//div[contains(text(), 'Create account')]"
            target_div = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, target_div_xpath))
            )
            target_div.click()
            print("已点击Create account")

            # 定位并点击第二个元素（Ronin）
            Ronin_xpath = "//div[contains(text(), 'Ronin')]"
            Ronin_div = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, Ronin_xpath))
            )
            Ronin_div.click()
            print("已点击Ronin")

            time.sleep(2)
            # 定位并点击第三个元素（Ronin Browser Extension）
            second_div_xpath = "//span[@class='whitespace-nowrap' and contains(text(), 'Ronin Browser Extension')]"
            second_div = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, second_div_xpath))
            )
            second_div.click()
            print("第三个元素Ronin Browser Extension已经找到并点击")

            #保存当前窗口话柄
            second_window = driver.current_window_handle

            # 等待新窗口打开
            WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)
            new_window = [h for h in driver.window_handles if h != main_window][0]
            driver.switch_to.window(new_window)
            print("已切换到新窗口")

            #点击Connect按钮
            connect_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "button._btn_16mny_28"))
            )
            connect_button.click()
            print("已点击Connect按钮")

            # 回到第二个标签页(点击第二个标签)
            print("回到第二个标签页")
            driver.switch_to.window(second_window)
            print("已切换回第二个窗口")

            #点击Sign in按钮
            sign_in_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "//*[@id=’headlessui-dialog-panel-:r1:‘]/div/div[2]/div/div/div[2]/button[2]"))
            )
            sign_in_button.click()
            print("已点击Sign in按钮")

            # 等待页面 URL 变化
            old_url = driver.current_url
            WebDriverWait(driver, 15).until(lambda d: d.current_url != old_url)
            print(f"页面 URL 已变化为 {driver.current_url}")

            # 等待页面加载完成
            WebDriverWait(driver, 15).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "div.wallet-module_wallet-balance__3-j3D"))
            )
            print("页面加载完成")







            # # 等待新窗口关闭
            # WebDriverWait(driver, 15).until(lambda d: len(d.window_handles) == 1)
            # driver.switch_to.window(main_window)
            # print("新窗口已关闭，返回主窗口")

            # # 等待页面 URL 变化
            # old_url = driver.current_url
            # WebDriverWait(driver, 15).until(lambda d: d.current_url != old_url)
            # print(f"页面 URL 已变化为 {driver.current_url}")

            # connect_clicked = False
            # sign_clicked = False
            #
            # # 持续检查 Connect 和 Sign 按钮
            # while not (connect_clicked and sign_clicked):
            #     try:
            #         if not connect_clicked:
            #             connect_button = WebDriverWait(driver, 5).until(
            #                 EC.element_to_be_clickable((By.CSS_SELECTOR, "button._btn_16mny_28"))
            #             )
            #             connect_button.click()
            #             print("已点击Connect按钮")
            #             connect_clicked = True
            #             WebDriverWait(driver, 15).until(
            #                 EC.staleness_of(connect_button)
            #             )
            #     except TimeoutException:
            #         pass
            #
            #     if connect_clicked:
            #         try:
            #             if not sign_clicked:
            #                 # 使用更精确的 CSS 选择器定位 Sign 按钮
            #                 sign_button = WebDriverWait(driver, 5).until(
            #                     EC.element_to_be_clickable(
            #                         (By.CSS_SELECTOR, "button.button-module_intent-primary__2RQGO._btn_16mny_28"))
            #                 )
            #                 sign_button.click()
            #                 print("已点击Sign按钮")
            #                 sign_clicked = True
            #         except TimeoutException:
            #             pass
            #
            # print("操作完成")
            # break

        except TimeoutException:
            print(f"尝试 {retries + 1}/{MAX_RETRIES} 次重试")
            retries += 1
            if retries >= MAX_RETRIES:
                print("达到最大重试次数")
                raise
            driver.refresh()

        except NoSuchWindowException:
            print("检测到窗口关闭异常，返回主窗口")
            driver.switch_to.window(main_window)
            continue






if __name__ == "__main__":
    driver = None
    try:
        from ronin import run_ronin_automation

        driver = run_ronin_automation()
        if not driver:
            raise Exception("钱包初始化失败")

        game_module_operations(driver)
        input("按回车键退出...")

    except Exception as e:
        print(f"程序终止: {e}")
    finally:
        if driver:
            input("按回车键退出浏览器...")
